/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package cn.com.photop.sap.contactme.frame;

import cn.com.photop.sap.contactme.common.CommonConstant;
import cn.com.photop.sap.contactme.common.CommonSession;
import cn.com.photop.sap.contactme.common.CommonWeather;
import cn.com.photop.sap.contactme.model.*;
import cn.com.photop.sap.contactme.service.CommonPropertiesService;
import cn.com.photop.sap.contactme.service.impl.ContactInfoService;
import cn.com.photop.sap.contactme.service.impl.UserService;
import cn.com.photop.sap.contactme.thread.WeatherThread;
import cn.com.photop.sap.contactme.util.IniUtil;
import cn.com.photop.sap.contactme.util.StringUtil;
import java.awt.Desktop;
import java.awt.event.WindowEvent;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;

/**
 *
 * @author Jiancheng.Zheng
 */
public class WeatherCityChangeFrame extends javax.swing.JFrame {

    private MainJFrame mainJFrame;
    //部门的集合 key 是公司
    private Map<String, List<Department>> mapDepartment;

    /**
     * Creates new form DataDetailFrame
     */
    public WeatherCityChangeFrame(MainJFrame mainJFrame) {
        this.mainJFrame = mainJFrame;
        mapDepartment = this.mainJFrame.getMapDepartment();
        initComponents();
        this.setLocationRelativeTo(null);

//        this.dispatchEvent(new WindowEvent(this,WindowEvent.WINDOW_CLOSING) );
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jButton1 = new javax.swing.JButton();
        jPanel1 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jComboBox1 = new javax.swing.JComboBox();
        jComboBox2 = new javax.swing.JComboBox();
        jButton2 = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("选择默认城市");
        setResizable(false);

        jButton1.setText("保存");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jLabel1.setText("省");

        jLabel2.setText("市");

        jComboBox1.removeAllItems();
        List<String> provinceList = CommonWeather.getInstance().provinceList;
        //provinceList.add(0, CommonConstant.CONSTANT_DEFAULT_PROVINCE);
        final int size = provinceList.size() + 1;
        String[] jModel = (String[]) CommonWeather.getInstance().provinceList.toArray(new String[size]);
        jComboBox1.setModel(new javax.swing.DefaultComboBoxModel(jModel));
        jComboBox1.insertItemAt(CommonConstant.CONSTANT_DEFAULT_PROVINCE, 0);
        jComboBox1.setSelectedIndex(0);
        jComboBox1.addItemListener(new java.awt.event.ItemListener() {
            public void itemStateChanged(java.awt.event.ItemEvent evt) {
                jComboBox1ItemStateChanged(evt);
            }
        });
        jComboBox1.addAncestorListener(new javax.swing.event.AncestorListener() {
            public void ancestorMoved(javax.swing.event.AncestorEvent evt) {
            }
            public void ancestorAdded(javax.swing.event.AncestorEvent evt) {
            }
            public void ancestorRemoved(javax.swing.event.AncestorEvent evt) {
                jComboBox1AncestorRemoved(evt);
            }
        });

        jComboBox2.insertItemAt(CommonConstant.CONSTANT_DEFAULT_CITY, 0);
        jComboBox2.setSelectedIndex(0);
        jComboBox2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jComboBox2ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(jLabel1)
                        .addGap(18, 18, 18)
                        .addComponent(jComboBox1, 0, 203, Short.MAX_VALUE))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(jLabel2)
                        .addGap(18, 18, 18)
                        .addComponent(jComboBox2, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(35, 35, 35)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(jComboBox2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(21, Short.MAX_VALUE))
        );

        jButton2.setText("取消");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(61, 61, 61)
                        .addComponent(jButton1)
                        .addGap(47, 47, 47)
                        .addComponent(jButton2)))
                .addContainerGap(49, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButton1)
                    .addComponent(jButton2))
                .addContainerGap(18, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    /**
     * 保存
     *
     * @param evt
     */
    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        String message = "";
        String province = (String) jComboBox1.getSelectedItem();
        if (CommonConstant.CONSTANT_DEFAULT_PROVINCE.equals(province)) {
            message = "请选择省";
            javax.swing.JOptionPane.showConfirmDialog((java.awt.Component) null,
                    message, "提示", javax.swing.JOptionPane.DEFAULT_OPTION);
            return;
        }
        String city = (String) jComboBox2.getSelectedItem();
        if (CommonConstant.CONSTANT_DEFAULT_CITY.equals(city)) {
            message = "请选择市";
            javax.swing.JOptionPane.showConfirmDialog((java.awt.Component) null,
                    message, "提示", javax.swing.JOptionPane.DEFAULT_OPTION);
            return;
        }
        
        String path = CommonPropertiesService.getValue( "IniFilePath" );//".\\res\\config.ini";
        path = CommonSession.getProjectPath() + path;
        String city_id = IniUtil.getPropValue(path, "city");//"101230101";//getCityIdByIP();
        if (StringUtil.isNull(city_id)) {
            city_id = CommonConstant.CONSTANT_DEFAULT_DEFAULT_CITY_CODE;
        };

        List<City> cityList = CommonWeather.getInstance().cityDataMap.get(province);
        for (int i = 0; i < cityList.size(); i++) {
            if (cityList.get(i).getName().equals(city)) {
                city_id = cityList.get(i).getCode();
                break;
            }
        }

        //天气预报更新
        new WeatherThread( this.mainJFrame,city_id ).start();
        //把配置信息保存到ini文件中取
        Map<String,String> iniMap = new HashMap<String,String>();
        iniMap.put("city", city_id);
        IniUtil.setPropValues(path, iniMap);
        setVisible(false);
        dispose();



    }//GEN-LAST:event_jButton1ActionPerformed

    /**
     * 取消按钮
     *
     * @param evt
     */
    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
        setVisible(false);
        dispose();
    }//GEN-LAST:event_jButton2ActionPerformed

    private void jComboBox1ItemStateChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_jComboBox1ItemStateChanged
        String selectedItem = (String) jComboBox1.getSelectedItem();
        if (CommonSession.getGroupName().equals(selectedItem)) {
            jComboBox2.removeAllItems();
            jComboBox2.insertItemAt(CommonConstant.CONSTANT_DEFAULT_CITY, 0);
            jComboBox2.setSelectedIndex(0);
            return;
        }
        //部门的集合 key 是公司
//        String province = (String)CommonWeather.getInstance().provinceList.get( selectedItem );
        List<City> listCity = CommonWeather.getInstance().cityDataMap.get(selectedItem);
//        listDepartment.add(0, "All");
        List<String> cityStrList = new ArrayList<String>();
        for (int i = 0; i < listCity.size(); i++) {
            cityStrList.add(listCity.get(i).getName());
        }
        int size = cityStrList.size();
        if (size > 0) {
            String[] jModel = (String[]) cityStrList.toArray(new String[size]);
            jComboBox2.removeAllItems();
            jComboBox2.setModel(new javax.swing.DefaultComboBoxModel(jModel));
            jComboBox2.insertItemAt(CommonConstant.CONSTANT_DEFAULT_CITY, 0);
            jComboBox2.setSelectedIndex(0);
        } else {
            jComboBox2.removeAllItems();
            jComboBox2.insertItemAt(CommonConstant.CONSTANT_DEFAULT_CITY, 0);
            jComboBox2.setSelectedIndex(0);
        }
    }//GEN-LAST:event_jComboBox1ItemStateChanged

    private void jComboBox2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jComboBox2ActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_jComboBox2ActionPerformed

    private void jComboBox1AncestorRemoved(javax.swing.event.AncestorEvent evt) {//GEN-FIRST:event_jComboBox1AncestorRemoved
        // TODO add your handling code here:
    }//GEN-LAST:event_jComboBox1AncestorRemoved

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /*
         * Set the Nimbus look and feel
         */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /*
         * If Nimbus (introduced in Java SE 6) is not available, stay with the
         * default look and feel. For details see
         * http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(WeatherCityChangeFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(WeatherCityChangeFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(WeatherCityChangeFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(WeatherCityChangeFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /*
         * Create and display the form
         */
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                try {
                    new WeatherCityChangeFrame(new MainJFrame()).setVisible(true);
                } catch (FileNotFoundException ex) {
                    Logger.getLogger(WeatherCityChangeFrame.class.getName()).log(Level.SEVERE, null, ex);
                } catch (IOException ex) {
                    Logger.getLogger(WeatherCityChangeFrame.class.getName()).log(Level.SEVERE, null, ex);
                } catch (Exception ex) {
                    Logger.getLogger(WeatherCityChangeFrame.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JComboBox jComboBox1;
    private javax.swing.JComboBox jComboBox2;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JPanel jPanel1;
    // End of variables declaration//GEN-END:variables

    protected void processWindowEvent(WindowEvent e) {
        if (e.getID() == WindowEvent.WINDOW_CLOSING) {
            /*
             * 关闭当前窗体 如果省略此句，那么就禁用了关闭按钮
             */

            this.dispose();
        } else {
            super.processWindowEvent(e);
        }
    }
}
